package com.cx.controller;

import com.cx.pojo.City;
import com.cx.service.CityService;
import com.cx.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/city")
public class CityController {

    @Autowired
    private CityService cityService;

    @Autowired
    private CountryService countryService;

    @GetMapping("/list")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/pages/cit/list");
        modelAndView.addObject("citys",cityService.findAll());
        return modelAndView;
    }

    @GetMapping("/page/{pageNumber}/{number}")
    public ModelAndView pages(@PathVariable (name = "pageNumber") Integer pageNumber,@PathVariable (name = "number") Integer number){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/pages/cit/pageslist");
        modelAndView.addObject("page",cityService.findPages(pageNumber,number));
        return modelAndView;
    }

    @GetMapping("/{cityid}")
    public ModelAndView delete(@PathVariable (name = "cityid") Integer cityid){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/pages/cit/edit");
        modelAndView.addObject("edit",cityService.findByIdAndCountry(cityid).get("city"));
        modelAndView.addObject("country",cityService.findByIdAndCountry(cityid).get("country"));
        return modelAndView;
    }

    @GetMapping("/delete/{cityid}")
    public ModelAndView deletes(@PathVariable (name = "cityid") Integer cityid){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/city/page/1/3");
        modelAndView.addObject("edit",cityService.delete(cityid));
        return modelAndView;
    }

    @PostMapping("/update")
    public ModelAndView update(City city){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("edit",cityService.update(city));
        modelAndView.addObject("edit",cityService.findByIdAndCountry(city.getCityid()));
        modelAndView.setViewName("redirect:/city/page/1/3");
        return modelAndView;
    }

    @PostMapping("/add")
    public ModelAndView add(City city){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("edit",cityService.add(city));
        modelAndView.setViewName("redirect:/city/page/1/3");
        return modelAndView;
    }

    @PostMapping("/addBefore")
    public ModelAndView adds(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/pages/cit/insert");
        modelAndView.addObject("country",countryService.selectByCountry());
        return modelAndView;
    }
}
